package yxy.game.pm2.command.wuchao;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.WuchaoMessage;
import yxy.game.pm2.module.wuchao.WuchaoHandle;
import yxy.game.pm2.module.wuchao.WuchaoModule;

/** 乌巢 乌巢去往下一关 */
@MessageType(proto = Command.WuchaoNextStage, classtype = WuchaoMessage.WuchaoNextStageRequest.class)
public class CMD_WuchaoNextStage extends Command<WuchaoMessage.WuchaoNextStageRequest> {

	@Override
	public void execute(MessageSource messageSource, WuchaoMessage.WuchaoNextStageRequest request) {
		String playerCode = messageSource.getTag();

		WuchaoMessage.WuchaoNextStageResponse.Builder response = WuchaoMessage.WuchaoNextStageResponse.newBuilder();

		WuchaoModule wuchaoModule = WuchaoModule.get(playerCode);
		if (wuchaoModule.getStage() <= 0) {
			send(messageSource, response, Result.WuchaoNotStart);// 没有开始挑战
			return;
		}
		try {
			if (wuchaoModule.tryLock()) {
				Result result = new WuchaoHandle().nextStage(wuchaoModule);
				if (!result.equals(Result.Success)) {
					send(messageSource, response, result);
					return;
				}

				// 发UI界面
				{
					WuchaoMessage.WuchaoUIResponse.Builder resp = WuchaoMessage.WuchaoUIResponse.newBuilder();
					result = new WuchaoHandle().info(playerCode, resp);
					send(messageSource, resp, result);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			wuchaoModule.unlock();
		}

	}

	private void send(MessageSource messageSource, WuchaoMessage.WuchaoNextStageResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}

	private void send(MessageSource messageSource, WuchaoMessage.WuchaoUIResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}